package cn.wx.common.configuration;

import cn.wx.common.WxServiceRegister;
import cn.wx.common.WxServiceRegisterImpl;
import cn.wx.common.WxServiceRegisterPostProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.annotation.Order;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Objects;

/**
 * 微信配置类
 *
 * @author: sunshaoping
 * @date: Create by in 3:41 下午 2020/5/25
 */
@Order(1)
@Configuration
public class WxConfiguration implements ApplicationListener<ContextRefreshedEvent> {


    private List<WxServiceRegisterPostProcessor> wxServiceRegisterPostProcessors;

    @Bean
    @ConditionalOnMissingBean
    public WxServiceRegister wxServiceRegister(ConfigurableBeanFactory beanRegistry) {
        return new WxServiceRegisterImpl(beanRegistry);
    }

    @PostConstruct
    public void init() {

    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {

        if (Objects.isNull(wxServiceRegisterPostProcessors)) {
            return;
        }
        ApplicationContext applicationContext = event.getApplicationContext();
        WxServiceRegister wxServiceRegister = applicationContext.getBean(WxServiceRegister.class);
        for (WxServiceRegisterPostProcessor postProcessor : wxServiceRegisterPostProcessors) {
            postProcessor.processor(wxServiceRegister);
        }
    }


    @Autowired(required = false)
    public void setWxServiceRegisterPostProcessors(List<WxServiceRegisterPostProcessor> wxServiceRegisterPostProcessors) {
        this.wxServiceRegisterPostProcessors = wxServiceRegisterPostProcessors;
    }
}
